<template>
  <!--工序参数记录弹框-->
  <div class="work_stage_param_record">
    <el-dialog
      title="参数记录"
      width="1400px"
      :visible.sync="dialogTableVisible"
      v-dialogDrag
      :close-on-click-modal="false"
      :before-close="_close"
      customClass="mes_dialog">
      <div class="param_cont" v-loading="isLoading || !Object.keys(recordData).length">
        <div class="param_left">
          <div class="record_type mes_tabs_btn">
            <div class="mes_tab_btn2">
              <span
                class="mes_tab_item"
                :class="{is_active: recordType === 'more',is_disabled: !isMore}"
                @click="_recordType('more')">批量记录</span>
              <span
                class="mes_tab_item"
                :class="{is_active: recordType === 'one'}"
                @click="_recordType('one')">单件记录</span>
            </div>
          </div>
          <div class="table_container">
            <el-table
              ref="batchTabel"
              border
              max-height="460"
              @current-change="handleCurrentChange"
              :data="batchList">
              <el-table-column
                align="center"
                v-if="recordType === 'one'"
                :resizable="false"
                width="40">
                <template slot-scope="scope">
                  <span class="radio_item" :class="{is_active: scope.row.workstageId === workstageId}">
                    <i class="radio_center"></i>
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="turnoverNumber"
                label="周转码"
                min-width="120"
                show-overflow-tooltip
                align="center">
              </el-table-column>
              <el-table-column
                prop="serialNumber"
                label="序列号"
                min-width="100"
                show-overflow-tooltip
                align="center">
              </el-table-column>
              <el-table-column
                prop="materialNumber"
                label="物料编码"
                min-width="100"
                show-overflow-tooltip
                align="center">
              </el-table-column>
              <el-table-column
                prop="materialName"
                label="物料名称"
                min-width="100"
                show-overflow-tooltip
                align="center">
              </el-table-column>
              <el-table-column
                prop="quantity"
                label="计划数量"
                min-width="80"
                show-overflow-tooltip
                align="center">
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="param_right">
          <param-record ref="ParamRecord"
                        v-if="Object.keys(recordData).length"></param-record>
        </div>
      </div>
      <span slot="footer" class="mes_btn">
        <el-button type="primary" @click="submit(true)">提交</el-button>
        <el-button @click="_close">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {ParamRecord} from './index'

export default {
  name: 'WorkStageParamRecord',
  components: {
    ParamRecord
  },
  data() {
    return {
      // 显示隐藏
      dialogTableVisible: false,
      // 加载中
      isLoading: false,
      // 模板信息
      paramTemplate: {},
      // 模板设备列表
      paramDeviceList: [],
      // 模板记录信息
      recordData: {},
      // 选择的周转批次列表
      selectData: [],
      // 当前记录类型
      recordType: 'more',
      // 单个记录时的当前工序id
      workstageId: '',
      // 是否允许批量记录
      isMore: true,
      // 是否保存过
      isSave: false,
      // 工序number
      workstageNumber: '',
    }
  },
  computed: {
    // 批次列表
    batchList() {
      return this.paramTemplate.batchList || []
    }
  },
  methods: {
    // 显示弹框并初始化数据，提供给父组件的方法
    openDialog(data) {
      if (data.length < 1) return
      // 初始化数据
      this.dialogTableVisible = true
      this.isLoading = true
      this.selectData = data
      this.workstageNumber = data[0].workstageNumber
      if (this.selectData.length === 1) {
        // 只有一个批次时，只能单件记录
        this.recordType = 'one'
        this.workstageId = this.selectData[0].id
        this.isMore = false
      } else {
        // 多个批次，可以批量记录
        this.recordType = 'more'
        this.isMore = true
      }
      this.init()
    },
    // 获取设备列表
    getDeviceList() {
      let workstageIds = this.recordType === 'one' ? this.workstageId : this.selectData.map(item => item.id).join(',')
      return this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/workstagerecordtemplate/workstageRecordTemplate/devicelist',
        data: {
          'workstageIds': workstageIds
        },
        noCommit: true
      }).then(res => {
        this.paramDeviceList = res.data || []
      })
    },
    // 获取参数记录信息
    getRecordsInfo() {
      let ids = this.selectData.map(item => item.id)
      return this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/workstagerecordtemplate/workstageRecordTemplate/batchretrieverecord',
        data: {
          workstageIds: ids.join(',')
        },
        noCommit: true
      }).then(res => {
        this.paramTemplate = res.data || {}
      }).catch(() => {
        this.paramTemplate = {}
      }).finally(() => {
        this.$nextTick(() => {
          this.$refs.batchTabel.doLayout()
        })
      })
    },
    // 显示记录表
    async showRecord() {
      await this.getDeviceList()
      // 批量记录过
      this.recordData = {
        // 已记录信息
        records: '',
        // 模板信息
        paramTemplate: this.paramTemplate.blank || {},
        // 设备列表
        deviceList: this.paramDeviceList
      }
      this.recordData.records = this.paramTemplate.records
      // 显示右侧记录表
      this.$nextTick(() => {
        this.$refs.ParamRecord.initParam(this.recordData, this.workstageNumber)
      })
    },
    // 初始化方法
    async init() {
      await this.getRecordsInfo()
      // 获取设备列表及参数记录信息后显示右侧记录表
      this.showRecord()
      this.isLoading = false
    },
    // 单行选中
    handleCurrentChange(row) {
      // 当前是批量记录，当前行不存在，点击已选中行则不执行
      if (this.recordType === 'more' || !row || this.workstageId === row.workstageId) return
      if (this.$refs.ParamRecord.isEdit) {
        // 已修改右侧记录表
        this.$confirm('检测到未保存的内容, 是否放弃修改?', '关闭提示', {
          distinguishCancelAndClose: true,
          confirmButtonText: '保存',
          cancelButtonText: '放弃修改',
          confirmButtonClass: 'el-button--danger',
          customClass: 'mes_confirm',
          type: 'warning'
        }).then(() => {
          // 点击保存
          this.submit()
        }).catch(action => {
          if (action === 'cancel') {
            // 点击放弃修改
            this.workstageId = row.workstageId
            this.showRecord()
          } else {
            // 直接关闭弹窗
            this.$refs.batchTabel.setCurrentRow()
          }
        })
      } else {
        // 未修改右侧记录表
        this.workstageId = row.workstageId
        this.showRecord()
      }
    },
    // 切换记录类型
    _recordType(val) {
      // 点击当前选中记录类型无效
      if (this.recordType === val) return
      // 如果不能批量记录则点击批量记录无效
      if (!this.isMore && val === 'more') return
      if (this.$refs.ParamRecord.isEdit) {
        // 记录表有修改
        this.$confirm('检测到未保存的内容, 是否放弃修改?', '关闭提示', {
          distinguishCancelAndClose: true,
          confirmButtonText: '保存',
          cancelButtonText: '放弃修改',
          confirmButtonClass: 'el-button--danger',
          customClass: 'mes_confirm',
          type: 'warning'
        }).then(() => {
          // 点击保存
          this.submit()
        }).catch(action => {
          if (action === 'cancel') {
            // 点击放弃修改
            this.showCurRecordItem(val)
          }
        })
      } else {
        // 未修改记录表
        this.showCurRecordItem(val)
      }
    },
    // 显示当前记录表
    showCurRecordItem(val) {
      this.recordType = val
      // 如果切换到单件记录，则选中第一个批次工序
      if (this.recordType === 'one') this.workstageId = this.batchList[0].workstageId
      this.showRecord()
    },
    // 格式化记录表数据
    formatRecord() {
      // 获取记录表信息
      let recordsList = this.$refs.ParamRecord.recordsList
      let paramRecord = recordsList.map(item => {
        let recordItem = item.inventory.map(item1 => {
          // 把选项类型的可选值已逗号拼接
          let obj = Object.assign({}, item1)
          if (obj.typeValue === 'Selection') {
            obj.selections = obj.selections.join(',')
          }
          // 删除类型以及单位的Label、Value
          delete obj.typeLabel
          delete obj.typeValue
          delete obj.unitLabel
          delete obj.unitValue
          return obj
        })
        return {
          name: item.name, // 模板名称
          inventory: recordItem // 记录表数据
        }
      })
      return JSON.stringify(paramRecord)
    },
    // 格式化保存数据
    postData() {
      let postData = {
        workstageIds: '', // 批次工序ID
        secretLevelId: this.paramTemplate.secretLevelId, // 模板密级Id
        paramRecord: this.formatRecord() // 参数记录Json
      }
      if (this.recordType === 'more') {
        // 批量记录
        postData.workstageIds = this.selectData.map(item => item.id).join(',')
      } else if (this.recordType === 'one') {
        // 单件记录
        postData.workstageIds = this.workstageId
      }
      return postData
    },
    // 保存
    submit(type) {
      if (this.saveState) return
      this.saveState = true
      let postData = this.postData()
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/workstagerecordtemplate/workstageRecordTemplate/batchsaveparam',
        data: postData,
        noCommit: true
      }).then(() => {
        this.saveSucess(postData.paramRecord, type)
      }).finally(() => {
        this.saveState = false
      })
    },
    // 保存成功回调
    saveSucess(paramRecord, type) {
      if (this.recordType === 'one' && !type) {
        // 点击提交
        this.isSave = true
        this.paramTemplate.records = paramRecord
        this.$refs.ParamRecord.isEdit = false
        this.isMore = false
        this.$refs.batchTabel.setCurrentRow()
        this.$message({
          type: 'success',
          message: '参数记录保存成功',
          duration: 1500,
          center: true
        })
      } else {
        // 点击保存
        this.$emit('submitSuccess')
        this._close()
        this.$message({
          type: 'success',
          message: '参数记录成功',
          duration: 1500,
          center: true
        })
      }
    },
    // 关闭清空
    _close() {
      this.dialogTableVisible = false
      this.paramTemplate = {}
      this.paramDeviceList = []
      this.recordData = {}
      if (this.isSave) {
        this.$emit('submitSuccess')
        this.isSave = false
      }
    }
  }
}
</script>

<style lang="less">
  .work_stage_param_record {
    .mes_dialog .el-dialog__body {
      padding: 0px 20px;
    }
    .param_cont {
      .param_left {
        .is_disable {
          box-shadow: none !important;
          .el-radio-button__inner {
            background-color: #f5f7fa !important;
            border-color: #dce0e9 !important;
            color: #a1b1c1 !important;
          }
        }
        .table_container {
          .el-radio__label {
            display: none;
          }
        }
      }
    }
  }
</style>
<style scoped lang="less">
  .work_stage_param_record {
    .param_cont {
      display: flex;
      width: 100%;
      .param_left {
        flex: 0 0 42%;
        width: 42%;
        overflow: hidden;
        box-sizing: border-box;
        padding: 20px 10px 20px 0px;
        border-right: 1px solid #ddd;
        .mes_tab_btn2 {
          line-height: 30px;
          overflow: hidden;
          display: flex;
          background-color: #ffffff;
          box-sizing: border-box;
          border-radius: 2px;
          border: 1px solid #dce0e9;
          .mes_tab_item {
            flex: 0 0 50%;
            text-align: center;
            color: #7e8e9f;
            border-left: 1px solid #dce0e9;
            cursor: pointer;
            &:first-child {
              border-left: none;
            }
            &.is_active {
              background-color: #00b4ff;
              color: #fff;
            }
            &.is_disabled {
              background-color: #f5f7fa;
              color: #a1b1c1;
              cursor: not-allowed;
            }
          }
        }
        .table_container {
          width: 100%;
          .radio_item {
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 12px auto 0;
            border: 1px solid #dcdfe6;
            border-radius: 100%;
            width: 14px;
            height: 14px;
            .radio_center {
              display: inline-block;
              vertical-align: middle;
              border-radius: 100%;
              width: 4px;
              height: 4px;
              background-color: #fff;
            }
            &.is_active {
              background-color: #409eff;
            }
          }
        }
        .record_type {
          margin-bottom: 20px;
        }
      }
      .param_right {
        flex: 0 0 58%;
        width: 58%;
        overflow: hidden;
        padding: 20px 0px 20px 10px;
        box-sizing: border-box;
      }
    }
  }
</style>
